package nc.oa.login;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryptor {
	
	private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String CHARSET_NAME = "UTF-8";

    private SecretKeySpec key;

    public AESEncryptor(String secretKey) {
        key = new SecretKeySpec(secretKey.getBytes(), "AES");
    }

    /**
     * 加密
     * @param data
     * @return
     * @throws Exception
     */
    public String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(data.getBytes(CHARSET_NAME));
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    /**
     * 解密
     * @param encryptedData
     * @return
     * @throws Exception
     */
    public String decrypt(String encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedData, CHARSET_NAME);
    }

	public static void main(String[] args) {
		String client_id = "OA";//erp提供第三方系统编码
		String client_security = "abcdefghijklmnop";//erp提供的第三方系统密钥
		String usercode = "OA"; //单点登录用户编码
		long ts = System.currentTimeMillis();//时间戳
		//按顺序拼接字符串，注意不要有空格
		String sprStr = "client_id:"+ client_id +"client_security:"+ client_security +"usercode:"+ usercode +"ts:"+ts;
		
		AESEncryptor aes = new AESEncryptor(client_security);
		System.out.println("未加密字符串：" + sprStr);
		
		String sign = "";
		try {
			//加密
			String encryptedStr = aes.encrypt(sprStr);
			System.out.println("加密后字符串：" + encryptedStr);
			//base64编码
			String base64 = Base64.getEncoder().encodeToString(encryptedStr.getBytes());
			sign = base64;
			System.out.println("base64编码后字符串：" + base64);
			
			//base64解密
			String deco_str = new String(Base64.getDecoder().decode(base64));
			System.out.println("base64解码后字符串：" + deco_str);
			//解密
			String decryptedStr = aes.decrypt(deco_str);
			System.out.println("解密后字符串：" + decryptedStr);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//单点登录erp的url
		String red_url = "http://127.0.0.1:3006/service/SSOLogin?usercode=cm&is2App=false&sign=" + sign;
		//String red_url = "http://erp.gsht.com/service/SSOLogin?usercode=WMS&is2App=false&sign=" + sign;
		System.out.println(red_url);

	}

}
